/****************************************************
          File Name:52-1.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sun 21 Sep 2014 09:18:56 AM CST
*****************************************************/

#include"mq.h"

int main(int argc,char *argv[])
{
    mqd_t mq;
    int opt,status;
    int flag=O_RDONLY;
    struct mq_attr attr;
    char *buf;
    struct timespec timeout;

    if(argc<3 || strcmp(argv[1],"--help")==0)
    {
        printf("%s /mq timeout\nor\n%s /mq timeout -x (O_NONBLOCK)\n",argv[0],argv[0]);
        exit(EXIT_FAILURE);
    }

    if(argc>3 && argv[3][1]=='x')
        flag|=O_NONBLOCK;

    if((mq=mq_open(argv[1],flag))==(mqd_t)-1)
        err("mq_open");
    if(mq_getattr(mq,&attr)==-1)
        err("getattr");   

    buf=malloc(attr.mq_msgsize);
    if(buf==NULL)
        err("malloc");

    timeout.tv_sec=atoi(argv[2]);
    timeout.tv_nsec=0;

    for(;;)
    {
        status=mq_timedreceive(mq,buf,attr.mq_msgsize,0,&timeout);
        if(status==-1)
        {
            if(errno==ETIMEDOUT)
            {
                printf("time out\n");
                break;
            }
            err("receive");
        }
        if(write(STDOUT_FILENO,buf,attr.mq_msgsize)==-1)
            err("write");
    }
    exit(EXIT_SUCCESS);
}
